import { createRequestPromise } from '../utils/request';
// import mockStructure from '../mock/sturcture';

export const getStructure = () => createRequestPromise('STRUCTURE_URL')
  // 接口返回的数据
  .then((res) => {
    const depts = []; // 爸爸们
    const subDepts = []; // 儿子们

    // 找爸爸
    for (const dept of res.depts) {
      if (!dept.pid) {
        depts.push({
          ...dept,
          depts: [],
        });
      } else {
        subDepts.push(dept);
      }
    }

    // 找漏掉的爸爸
    // 给所有的爸爸添加儿子
    for (const subDept of subDepts) {
      const pid = subDept.pid;
      const parent = depts.find((dept) => {
        return dept.id === pid;
      });
      if (parent) {
        parent.depts.push(subDept);
      } else {
        depts.push({
          ...subDept,
          depts: [],
        });
      }
    }

    return {
      ...res,
      depts,
    };
  })
  // 改造数据
  .then((res) => {

    function mapper (originDepts = []) {
      return originDepts.map((originDept) => {
        return {
          label: originDept.name,
          manager: originDept.manager,
          id: originDept.id,
          children: mapper(originDept.depts),
        };
      });
    }

    return {
      ...res,
      depts: mapper(res.depts),
    };
  });
